<template>
  <!-- 账号列表 -->
  <section class="add">
    <!-- 头部筛选区域 -->
    <section class="top">
      <el-page-header title="返回列表" @back="goBack">
        <template #content>
          <span class="text-large font-600 mr-3"> {{ headerContent }} </span>
        </template>
      </el-page-header>
    </section>
    <section class="content">
      <el-form
        ref="ruleFormRef"
        :model="form"
        :rules="rules"
        label-position="top"
      >
        <el-row :gutter="100">
          <el-col :span="12">
            <el-form-item
              label="课程名称"
              prop="courseName"
              :label-width="80"
              required
            >
              <el-input
                v-model="form.courseName"
                autocomplete="off"
                placeholder="请输入课程名称"
              /> </el-form-item
          ></el-col>
          <el-col :span="12">
            <el-form-item label="展示首页" prop="field" :label-width="80">
              <el-switch
                v-model="form.homePage"
                :active-value="1"
                :inactive-value="0"
                active-text="是"
                inactive-text="否"
              /> </el-form-item
          ></el-col>
        </el-row>

        <el-row :gutter="100">
          <el-col :span="12">
            <el-form-item label="图片" prop="field" :label-width="80">
              <el-upload
                accept="image/*"
                :limit="1"
                :headers="uploadHeaders"
                :file-list="form.coursePicFile"
                :action="uploadFileUrl"
                list-type="picture-card"
                :on-success="handleUploadCoursePicSuccess"
                :on-remove="handleUploadCoursePicRemove"
              >
                <el-icon><Plus /></el-icon>
              </el-upload> </el-form-item
          ></el-col>
          <el-col :span="12">
            <el-form-item label="视频" prop="field" :label-width="80">
              <el-upload
                v-model:file-list="form.courseVideoFile"
                limit="1"
                accept="video/*"
                :action="uploadFileUrl"
                list-type="picture-card"
                :on-preview="handlePictureCardPreview"
                :on-remove="handleRemove"
              >
                <el-icon><Plus /></el-icon> </el-upload></el-form-item
          ></el-col>
        </el-row>

        <el-row :gutter="100">
          <el-col :span="12">
            <el-form-item
              label="课程类型"
              prop="courseType"
              :label-width="80"
              required
            >
              <el-select v-model="form.courseType" placeholder="请选择课程类型">
                <el-option
                  v-for="item in courseTypeList"
                  :key="item.id"
                  :label="item.courseName"
                  :value="item.id"
                />
              </el-select> </el-form-item
          ></el-col>
          <el-col :span="12">
            <el-form-item
              label="授课形式"
              prop="teachingFormatType"
              :label-width="80"
              required
            >
              <el-select
                v-model="form.teachingFormatType"
                placeholder="请选择授课形式"
              >
                <el-option
                  v-for="item in teachingFormatTypeList"
                  :key="item.id"
                  :label="item.courseName"
                  :value="item.id"
                />
              </el-select> </el-form-item
          ></el-col>
        </el-row>

        <el-row :gutter="100">
          <el-col :span="12">
            <el-form-item
              label="课程次数"
              prop="courseCount"
              :label-width="80"
              required
            >
              <el-input
                v-model="form.courseCount"
                placeholder="请输入课程次数"
              ></el-input> </el-form-item
          ></el-col>
          <el-col :span="12">
            <el-form-item label="价格" prop="price" :label-width="80" required>
              <el-input
                v-model="form.price"
                placeholder="请输入价格"
              ></el-input> </el-form-item
          ></el-col>
        </el-row>

        <el-row :gutter="100">
          <el-col :span="12">
            <el-form-item
              label="课程排序"
              prop="courseSort"
              :label-width="80"
              required
            >
              <el-input
                v-model="form.courseSort"
                placeholder="请输入课程排序"
              ></el-input> </el-form-item
          ></el-col>
        </el-row>

        <el-form-item label="内容" prop="courseIntroduction" :label-width="80">
          <wangEditer
            :html="form.courseIntroduction"
            :update="updateCourseIntroduction"
          ></wangEditer>
        </el-form-item>
      </el-form>
    </section>
    <section class="bottom mb-4">
      <el-button @click="goBack">取消</el-button>
      <el-button
        type="primary"
        :loading="isLoading"
        @click="submitForm(formRef)"
        >确认</el-button
      >
    </section>
  </section>
</template>

<script setup>
import { ref, reactive } from "vue";
import { useRoute, useRouter } from "vue-router";
import { uploadFile, uploadFileUrl } from "@/apis/file.js";
import { addRequest, updateRequest } from "@/apis/course.js";
import { queryListRequest as queryCourseTypeList } from "@/apis/courseType.js";
import { queryListRequest as queryTeachingFormatTypeList } from "@/apis/teachingFormatType.js";

import { userStore } from "@/stores/userInfo";
const userInfo = userStore();

import wangEditer from "../../components/wangEditer.vue";
const router = useRouter();
const route = useRoute();
const optionType = route.query.type;
// header的内容
let headerContent = "新增课程";
// form表单参数
const ruleFormRef = ref(null);
let form = reactive({
  courseName: "", //课程名称
  homePage: "0", //展示首页
  coursePic: "", //图片
  coursePicFile: [], //图片
  courseVideo: "", //视频
  courseVideoFile: [], //视频
  courseType: "", //课程类型
  courseSort: "", //课程排序
  teachingFormatType: "", //授课形式
  courseCount: "", //课程次数
  price: "", //价格
  courseIntroduction: "", //富文本内容
});
if (optionType == "edit") {
  headerContent = "编辑课程";
  let editObj = JSON.parse(route.query.rowData);
  console.error(editObj);
  form.id = editObj.id;
  Object.keys(form).forEach((item) => {
    if (editObj[item]) {
      form[item] = editObj[item];
      if (item == "coursePicFile" || item == "courseVideoFile") {
        form[item] = [];
        if (editObj[item]) {
          let path =
            window.location.origin +
            "/api/" +
            editObj[item].path.split("\\").pop();
          form[item] = [
            {
              name: path,
              url: path,
              uid: path,
            },
          ];
        }
      }
    }
  });
  console.error(form);
}
// form 表单规则
const rules = reactive({
  courseName: [
    { required: "true", message: "请输入课程名称", trigger: "blur" },
  ],
  courseType: [
    { required: "true", message: "请选择课程类型", trigger: "change" },
  ],
  teachingFormatType: [
    { required: "true", message: "请选择授课形式", trigger: "change" },
  ],
  courseCount: [
    { required: "true", message: "请输入课程数量", trigger: "blur" },
  ],
  price: [{ required: "true", message: "请输入价格", trigger: "blur" }],
});

// 课程类型列表
const courseTypeList = ref([]);
queryCourseTypeList().then((res) => {
  courseTypeList.value = res.data;
});
// 授课形式列表
const teachingFormatTypeList = ref([]);
queryTeachingFormatTypeList().then((res) => {
  teachingFormatTypeList.value = res.data;
});

// 上传文件token
const uploadHeaders = ref({
  token: userInfo.$state.token,
});
// 处理上传成功逻辑
const handleUploadCoursePicSuccess = (response, file, fileList) => {
  const newFile = {
    name: response.data.name,
    url: response.data.id,
    uid: response.data.id,
  };
  form.coursePicFile.push(newFile);
  form.coursePic = response.data.id;
};
const handleUploadCoursePicRemove = (file, fileList) => {
  // 处理删除文件的逻辑。
  const index = fileList.findIndex((item) => item.uid === file.uid);
  if (index !== -1) {
    fileList.splice(index, 1);
  }
};

// ** 更新富文本编辑器
const updateCourseIntroduction = (html) => {
  form.courseIntroduction = html;
};

// 提交loading
let isLoading = ref(false);
// form提交函数
const submitForm = () => {
  if (!ruleFormRef) return;
  ruleFormRef.value.validate(async (valid) => {
    if (valid) {
      // 打开loding
      isLoading.value = true;
      // 数据处理
      const data = Object.assign({}, form);
      delete data.coursePicFile;
      delete data.courseVideoFile;
      // 请求接口
      if (optionType == "edit") {
        await updateRequest(data);
      } else {
        await addRequest(data);
      }
      // 关闭loading
      isLoading.value = false;
      // 路由返回
      goBack();
    } else {
      console.log("error submit!");
      return false;
    }
  });
};
//  路由返回函数
const goBack = () => {
  router.back();
};
</script>
<style lang="less" scoped>
.add {
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
  .top {
    display: flex;
    .el-input {
      width: 300px;
      margin-right: 20px;
    }
  }
  .content {
    // width: 100%;
    flex: 1;
    overflow-x: hidden;
    overflow-y: scroll;
    padding: 20px;
    // margin-top: 20px;
    // margin-bottom: 20px;
  }
  .bottom {
    display: flex;
    justify-content: end;
  }
}
</style>
